package com.xiaomaoguai.crs.web.controller;

import com.xiaomaoguai.crs.common.model.ResponseModel;
import com.xiaomaoguai.crs.common.utils.StringEscapeEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ FileName: BaseController.java
 * @ Author: WeiHui-Z
 * @ Date: 2017/4/17 17:30
 * @ Version: v1.0.0
 */
public abstract class BaseController {

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        /*
         * 自动转换日期类型的字段格式
		 */
        binder.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        /*
         * 防止XSS攻击
		 */
        binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
    }

    private static final String JSP_PREFIX = "jsp/";

    private static final String HTML_PREFIX = "html/";

    private static final String VM_PREFIX = "";

    private static final String FTL_PREFIX = "ftl/";

    protected String renderHtml(String viewName) {
        return HTML_PREFIX + viewName;
    }

    protected String renderVm(String viewName) {
        return VM_PREFIX + viewName;
    }

    protected String renderFtl(String viewName) {
        return FTL_PREFIX + viewName;
    }

    protected String renderJsp(String viewName) {
        return JSP_PREFIX + viewName;
    }

    /**
     * ajax成功
     *
     * @return {Object}
     */
    public Object renderSuccess() {
        return new ResponseModel(true);
    }

    /**
     * ajax成功
     *
     * @param msg 消息
     * @return {Object}
     */
    public Object renderSuccess(String msg) {
        ResponseModel result = new ResponseModel();
        result.setSuccess(true);
        result.setMsg(msg);
        return result;
    }

    /**
     * ajax成功
     *
     * @param obj 成功时的对象
     * @return {Object}
     */
    public Object renderSuccess(Object obj) {
        ResponseModel result = new ResponseModel();
        result.setSuccess(true);
        result.setResult(obj);
        return result;
    }

    /**
     * ajax失败
     *
     * @param msg 失败的消息
     * @return {Object}
     */
    public Object renderError(String msg) {
        ResponseModel result = new ResponseModel();
        result.setMsg(msg);
        return result;
    }
}
